package training;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author liangzai
 * @Description:
 */
public class J25_8_4_Training {
    //水果成篮
    public int totalFruit(int[] fruits) {
        int n = fruits.length;
        int ans = 1;
        int[] f = new int[]{fruits[0], 0, 0}, s = new int[]{fruits[0], 0, 0};

        for (int i = 0; i < n; i++) {
            if (f[0] == s[0]) {
                if (fruits[i] == s[0]) {
                    f[2] = i;
                    s[2] = i;
                } else {
                    s = new int[]{fruits[i], i, i};
                }
                ans = Math.max(ans, i - f[1] + 1);
            } else
            if (f[0] != fruits[i] && s[0] != fruits[i]) {
                int idx = Math.min(s[2] + 1, f[2] + 1);
                f = new int[]{fruits[idx], idx , Math.max(f[2], s[2]) };
                s = new int[]{fruits[i], i, i};
                ans = Math.max(ans, i - f[1]);
            } else {
                if (f[0] == fruits[i]) {
                    f[2] = i;
                } else {
                    s[2] = i;
                }
                ans = Math.max(ans, i - f[1] + 1);
            }
        }
        return ans;
    }

    //描述绘画结果
    public List<List<Long>> splitPainting(int[][] segments) {
        List<List<Long>> result = new ArrayList<List<Long>>();
        long[][] change = new long[(int)(1e5 + 1)][2];
        for(int i = 0; i < segments.length; ++i) {
            change[segments[i][0]][0] += segments[i][2];
            change[segments[i][1]][1] -= segments[i][2];
        }
        long sum = 0;
        long start = 0;
        for(int i = 0; i < change.length; ++i) {
            if(change[i][0] != 0 || change[i][1] != 0) {
                if(sum == 0) {
                    start = i;
                }
                if(sum != 0) {
                    result.add(Arrays.asList(new Long[]{start, (long)i, sum}));
                    start = i;
                }
                sum += change[i][0] + change[i][1];
            }
        }
        return result;
    }
}
